package com.ztsoft.user.utils;

import com.github.tobato.fastdfs.domain.fdfs.MetaData;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;

/**
 * FastDFS客户端工具类
 */
@Component
public class FastDFSFileUtils {
    //从配置文件获取服务器IP地址及端口
    @Value("${tracker-server}")
    private String server;

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    /**
     * 文件解析
     *
     * @param file 文件对象
     * @return 调用文件上传方法
     * @throws IOException IO异常
     */
    public String uploadFile(MultipartFile file) throws IOException {
        if (file != null) {
            //获取文件的字节数组
            byte[] bytes = file.getBytes();
            //获取文件大小
            long fileSize = file.getSize();
            //获取上传时的文件名
            String originalFilename = file.getOriginalFilename();
            //获取文件扩展名
            String extension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);

            return this.uploadFile(bytes, fileSize, extension);
        }
        return null;
    }

    /**
     * 文件上传
     *
     * @param bytes     文件字节
     * @param fileSize  文件大小
     * @param extension 文件扩展名
     * @return 文件路径（卷名和文件名）
     */
    public String uploadFile(byte[] bytes, long fileSize, String extension) {
        //将字节数组转成字节输入流
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);

        //封装元数据信息
        Set<MetaData> metaDataSet = new HashSet<>();
        metaDataSet.add(new MetaData("author", "ztsoft"));
        metaDataSet.add(new MetaData("dateTime", LocalDateTime.now().toString()));

        //上传图片文件以及缩略图，返回了一个存储路径
        //参数：文件的输入流，文件的大小，文件扩展名，元数据信息（例如作者姓名）
        StorePath storePath = fastFileStorageClient.uploadFile(byteArrayInputStream, fileSize, extension, metaDataSet);

        return "http://" + server + "/" + storePath.getFullPath();
    }


    /**
     * 删除
     *
     * @param storePath
     */
    public void delete(String storePath) {
        if (StringUtils.isNotBlank(storePath)) {     //判断参数是否不为空
            fastFileStorageClient.deleteFile(storePath);
        }
    }

    /**
     * 删除
     *
     * @param group
     * @param path
     */
    public void delete(String group, String path) {
        fastFileStorageClient.deleteFile(group, path);
    }

    /**
     * 文件下载
     *
     * @param path 文件路径，例如：/group1/M00/00/00/itstyle.png
     */
    public byte[] downLoad(String path) {
        byte[] bytes = null;
        // 获取文件
        StorePath storePath = StorePath.parseFromUrl(path);
        if (StringUtils.isNotBlank(path)) {
            //获取group
            String group = storePath.getGroup();
            //获取路径
            String filePath = storePath.getPath();
            DownloadByteArray byteArray = new DownloadByteArray();
            bytes = fastFileStorageClient.downloadFile(group, filePath, byteArray);
        }
        return bytes;
    }

}